<template>
  <div class="add-dept">
    <el-dialog
      :title="form.id ? '编辑部门' : '添加部门'"
      :visible.sync="show"
      @close="handleCloseDialog"
    >
      <el-form ref="formAdd" :model="form" :rules="rules">
        <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="1-50个字符"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码" :label-width="formLabelWidth" prop="code">
          <el-input
            v-model="form.code"
            autocomplete="off"
            placeholder="1-50个字符"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" :label-width="formLabelWidth" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择负责人">
            <el-option
              v-for="v in employeeList"
              :key="v.id"
              :label="v.username"
              :value="v.username"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" :label-width="formLabelWidth" prop="introduce">
          <el-input
            v-model="form.introduce"
            autocomplete="off"
            placeholder="1-300个字符"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetEmployeeSimple } from '@/api/employees'
import {
  reqPostDepartment,
  reqGetDepartmentById,
  reqEditDepartmentById,
} from '@/api/departments'

export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    departsList: {
      required: true,
      type: Array,
    },
    nodeData: {
      required: true,
      type: Object,
    },
  },
  data() {
    const checkNameRepeat = (rule, value, callback) => {
      const arr = this.departsList.filter(item => item.pid === this.nodeData.id)
      const flag = arr.some(item => item.name === value)
      flag ? callback(new Error(`同级部门下已经有${value}部门`)) : callback()
    }
    const checkCodeRepeat = (rule, value, callback) => {
      const arr = this.departsList.filter(item => item.pid === this.nodeData.id)
      const flag = arr.some(item => item.code === value)
      flag ? callback(new Error(`已经有编码${value}的部门了`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        id: '', // 部门id
        pid: '', // 父部门id
      },
      formLabelWidth: '120px',
      show: false,
      employeeList: [],
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' },
        ],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' },
        ],
      },
    }
  },

  // 监听showDialog的改变,来控制对话框的显示与隐藏
  watch: {
    showDialog: {
      immediate: true,
      handler(val) {
        this.show = val
      },
    },
  },

  created() {
    // 调用方法
    this.getEmployeeList()
  },

  methods: {
    // 一、关闭弹出层
    handleCloseDialog() {
      this.$emit('closeDialog', false)
      this.$refs['formAdd'].resetFields()
      // 重置form
      this.form = {}
    },

    // 二、点击对话框的确认按钮触发事件
    handleConfirm() {
      // 1.校验对话框的的规则
      this.$refs['formAdd'].validate(async valid => {
        if (!valid) return this.$message.error('您还有需要填写的选项哦')
        // 2.判断是添加请求还是修改请求
        if (this.form.id) {
          // 2.1 有id说明要发送编辑请求
          await reqEditDepartmentById(this.form)
          this.$message.success('修改成功')
        } else {
          // 2.2 发送添加请求
          try {
            this.form.pid = this.nodeData.id
            await reqPostDepartment(this.form)
            this.$message.success('添加成功')
          } catch {
            this.$message.error('添加失败')
          }
        }
        // 3.通知父组件关闭对话框,通知父组件刷新数据
        this.$emit('closeDialog', false)
        this.$emit('upDateDept', this.nodeData)
      })
    },

    // 三、获取员工简单列表
    async getEmployeeList() {
      const data = await reqGetEmployeeSimple()
      // console.log(data)
      this.employeeList = data
    },

    // 四、根据id查询部门详情
    async getDepartment(id) {
      const data = await reqGetDepartmentById(id)
      // console.log(data)
      this.form = data
    },
  },
}
</script>
